package leetcode.problems.P7整数反转;

import java.util.Stack;

public class Reverse {
    public static void main(String[] args) {
        int x = -123;
        System.out.println(x % 10);
    }
}

// 利用异常处理
class Solution {
    public int reverse(int x) {
        boolean negative = x < 0;
        if (negative) {
            x = -x;
        }
        StringBuilder s = new StringBuilder(String.valueOf(x)).reverse();
        int result;
        try {
            result = Integer.parseInt(s.toString());
        } catch (Exception e) {
            return 0;
        }
        return negative ? -result : result;
    }
}

// 利用溢出判断，不断的乘10除10，(ans*10)/10 == ans

class Solution2 {
    public int reverse(int x) {
        int ans = 0;
        while (x != 0) {
            if ((ans * 10) / 10 != ans) return 0;
            ans = ans * 10 + x % 10;
            x /= 10;
        }
        return ans;
    }
}